//
//  UserAccountViewModel.swift
//  Weibo8023
//
//  Created by styshy on 15/12/9.
//  Copyright © 2015年 sz. All rights reserved.
//

import Foundation

class UserAccountViewModel{
    
    static let sharedUserAccount = UserAccountViewModel()
    
    var account:UserAccount?
    
    // 返回有效的accessToken
    var accessToken:String? {
        if isExpired == false{
            return account?.access_token
        }
        return nil
    }
    
    // 用户登录标记
    
    var userLogin:Bool{
        return account?.access_token != nil && !isExpired
    }
    
    // 保存路径
    var accountPath:String{
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        return (path as NSString).stringByAppendingPathComponent("account.plist")
    }
    
    // 头像路径
    var avatarUrl:NSURL{
        return NSURL(string: account?.avatar_large ?? "")!
    }
    
    
    // 判断accessToken是否过期
    private var isExpired:Bool{
        
        if account?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            // 代码执行到此，一定进行过比较！
            return false
        }
        
        return true
    }
    
    private init(){
        // 从沙盒解档数据，恢复当前数据 - 磁盘读写的速度最慢，不如内存读写效率高！
        account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount
        
        // 判断token是否过期
        if isExpired {
            print("已经过期")
            
            // 如果过期，清空解档的数据
            account = nil
        }

    }

}


// MARK: - 用户相关的网络方法
extension UserAccountViewModel{
    
    func loadAccessToken(code:String, finished:(isSuccessed:Bool) -> ()){
        NetworkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
            // 首先进行错误判断
            if error != nil {
                print("出错了")
                finished(isSuccessed: false)
                return
            }
            
            self.account = UserAccount(dict: (result) as! [String:AnyObject])
            self.loadUserInfo(self.account!, finished:finished )
            
        }
    }
    
    // 加载用户信息
    private func loadUserInfo(account:UserAccount, finished:(isSuccessed:Bool) -> ()){
        
        NetworkTools.sharedTools.loadUserInfo(account.uid!) { (result, error) -> () in
            if error != nil{
                print("用户加载错误")
                finished(isSuccessed: false)
                return
            }
            
            guard let dict = result as? [String:AnyObject] else{
                print("格式错误")
                finished(isSuccessed: false)
                return
            }
            account.screen_name = dict["screen_name"] as? String
            account.avatar_large = dict["avatar_large"] as? String
            
            NSKeyedArchiver.archiveRootObject(account, toFile: self.accountPath)
            
            finished(isSuccessed: true)
            
        }
        
    }
}
